<template>
    <div>
        <!-- 面包屑区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片主体内容 -->
        <el-card class="box-card">
            <!-- 搜索区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable @keyup.enter.native="searchUser"
                        @clear="searchUser">
                        <el-button @click="searchUser" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="openAddUser">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 用户列表 -->
            <el-table :data="userList" border stripe>
                <el-table-column type="index">
                </el-table-column>
                <el-table-column prop="username" label="姓名">
                </el-table-column>
                <el-table-column prop="email" label="邮箱">
                </el-table-column>
                <el-table-column prop="mobile" label="电话">
                </el-table-column>
                <el-table-column prop="role_name" label="角色">
                </el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="changeStatus(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                        <el-button @click="openEdit(scope.row.id)" type="primary" icon="el-icon-edit"
                            size="mini"></el-button>
                        <!-- 删除按钮 -->
                        <el-button @click="delUser(scope.row.id)" type="danger" icon="el-icon-delete"
                            size="mini"></el-button>
                        <!-- 分配角色按钮 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button @click="openSetRole(scope.row)" type="warning" icon="el-icon-setting"
                                size="mini"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>


        <!-- 添加用户的对话框 -->
        <el-dialog :close-on-click-modal="false" title="添加用户" :visible.sync="addDialogVisible" width="50%"
            @close="addDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑用户的对话框 -->
        <el-dialog :close-on-click-modal="false" title="编辑用户" :visible.sync="editDialogVisible" width="50%"
            @close="() => { editDialogVisible = false }">
            <!-- 内容主体区域 -->
            <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input disabled v-model="editForm.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配角色的对话框 -->
        <el-dialog :close-on-click-modal="false" title="分配角色" :visible.sync="roleDialogVisible" width="50%"
            @close="() => { roleDialogVisible = false }">
            <!-- 内容主体区域 -->
            <div>
                <p>当前的用户：{{ userInfo.username }}</p>
                <p>当前的角色：{{ userInfo.role_name }}</p>
                <p>
                    分配新角色：
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="roleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
export default {
    name: 'users',
    data() {

        // 验证邮箱的规则
        var checkEmail = (rule, value, cb) => {
            // 验证邮箱的正则表达式
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

            if (regEmail.test(value)) {
                // 合法的邮箱
                return cb();
            }

            cb(new Error("请输入合法的邮箱"));
        };

        // 验证手机号的规则
        var checkMobile = (rule, value, cb) => {
            // 验证手机号的正则表达式
            const regMobile =
                /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

            if (regMobile.test(value)) {
                return cb();
            }

            cb(new Error("请输入合法的手机号"));
        };

        return {
            userList: [],
            queryInfo: {
                query: '',
                pagesize: 10,
                pagenum: 1,
            },
            total: 0,
            addDialogVisible: false, // 控制添加用户的弹窗的显示和隐藏
            addFormRules: {
                username: [
                    { required: true, message: "请输入用户名", trigger: "blur" },
                    {
                        min: 3,
                        max: 10,
                        message: "用户名的长度在3~10个字符之间",
                        trigger: "blur",
                    },
                ],
                password: [
                    { required: true, message: "请输入密码", trigger: "blur" },
                    {
                        min: 6,
                        max: 15,
                        message: "用户名的长度在6~15个字符之间",
                        trigger: "blur",
                    },
                ],
                email: [
                    { required: true, message: "请输入用户邮箱", trigger: "blur" },
                    { validator: checkEmail, trigger: "blur" },
                ],
                mobile: [
                    { required: true, message: "请输入用户手机", trigger: "blur" },
                    { validator: checkMobile, trigger: "blur" },
                ],
            },
            addForm: {
                username: '',
                email: '',
                password: '',
                mobile: '',
            },
            editDialogVisible: false,
            editId: null,
            editForm: {
                username: '',
                email: '',
                mobile: '',
            },
            roleDialogVisible: false,
            selectedRoleId: null,
            userInfo: {
                role_name: '',
                username: '',
            },
            rolesList: [], // 角色列表
        }
    },
    created() {
        this.getUsers()
    },
    methods: {
        // 获取用户列表数据
        async getUsers() {
            const res = await this.$http.get('users', { params: this.queryInfo })
            console.log(res);
            if (res.status == 200) {
                this.userList = res.data.data.users
                this.total = res.data.data.total
            }
        },

        // 改变用户状态
        async changeStatus(info) {
            // const res = await this.$http.put(`users/${info.id}/state/${info.mg_state}`)
            // if(res.status == 200) {
            //     this.$message.success(res.data.meta.msg)
            // }
        },

        // 搜索用户
        searchUser() {
            this.queryInfo.pagenum = 1
            this.getUsers()
        },

        // 页容量改变的时候
        handleSizeChange(val) {
            this.queryInfo.pagesize = val
            this.getUsers()
        },

        // 页码变化的时候
        handleCurrentChange(val) {
            this.queryInfo.pagenum = val
            this.getUsers()
        },

        // 打开添加用户窗口
        openAddUser() {
            this.addDialogVisible = true
        },

        // 关闭添加用户的窗口
        addDialogClosed() {
            this.addDialogVisible = false
        },

        // 发送添加用户的请求
        addUser() {
            this.$refs.addFormRef.validate(async (valid) => {
                if (valid) {
                    const res = await this.$http.post('users', this.addForm)
                    // console.log(res);
                    if (res.status == 200) {
                        this.addDialogVisible = false
                        this.$message.success(res.data.meta.msg)
                        // 重新加载数据
                        this.getUsers()
                        // 重置添加用户的表单数据
                        this.$refs.addFormRef.resetFields()
                    }
                }
            })
        },

        // 删除用户
        delUser(id) {
            this.$confirm('确认删除该用户吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {

                // 发送删除请求
                const res = await this.$http.delete(`users/${id}`)
                // console.log(res);
                if (res.status == 200) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });

                    this.getUsers()
                }


            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },

        // 打开编辑弹窗
        async openEdit(id) {
            const res = await this.$http.get(`users/${id}`)

            // console.log(res);
            if (res.status == 200) {
                const { username, email, mobile } = res.data.data
                this.editForm = {
                    username,
                    email,
                    mobile
                }
                this.editId = id
            }

            this.editDialogVisible = true
        },

        // 编辑用户信息
        editUser() {
            this.$refs.edittFormRef.validate(async valid => {
                if (valid) {
                    const res = await this.$http.put(`users/${this.editId}`, this.editForm)
                    // console.log(res);
                    if (res.status == 200) {
                        // 成功编辑后重新加载数据
                        this.getUsers()

                        this.$message.success(res.data.meta.msg)
                        this.editDialogVisible = false
                        // 重置编辑表单数据
                        this.$refs.editFormRef.resetFields()
                    }
                }
            })
        },

        // 打开分配角色弹窗
        async openSetRole(info) {
            this.editId = info.id
            this.userInfo = {
                username: info.username,
                role_name: info.role_name
            }

            // 请求获取角色列表
            const res = await this.$http.get('roles')
            // console.log(res);
            if (res.status == 200) {
                this.rolesList = res.data.data.map(item => {
                    return {
                        id: item.id,
                        roleName: item.roleName
                    }
                })

                // const target = this.rolesList.find(item => item.roleName == info.role_name)
                // // console.log(target);
                // this.selectedRoleId = target.id
            }


            this.roleDialogVisible = true
        },

        // 分配角色
        async saveRoleInfo() {
            if (!this.selectedRoleId) {
                this.$message.error('未选择角色')
                return
            }

            const res = await this.$http.put(`users/${this.editId}/role`, { rid: this.selectedRoleId })
            // console.log(res);
            if (res.status == 200) {
                // 刷新数据
                this.getUsers()

                this.roleDialogVisible = false
                this.$message.success('设置成功')

            }
        }
    }
}
</script>
<style scoped></style>